package com.pet.server.ext.action.square;

import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.TreeMap;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.pet.server.ext.ActionBase;
import com.pet.server.ext.ApiError;
import com.pet.server.ext.Result;
import com.pet.server.ext.data.Constant;
import com.pet.server.ext.service.UserService;
import com.pet.server.ext.util.Parameters;
import com.pet.server.ext.util.Pinyin;
import com.pet.server.ext.util.StringUtil;

public class Breed extends ActionBase{

	public String code;
	public Breed(){
		 needCheckAuth =false;
	}
	
	@Override
	public void initParameters(Parameters params) throws ApiError {	
		code = params.getFieldValue("code");
        if(StringUtil.isEmpty(code)){
        	throw ApiError.Type.INVALID_PARAM.toException();
        }
	}
	
	@Override
	public Result invokeService() throws ApiError {
		JSONObject o = new JSONObject();
		UserService userService = new UserService();
		Constant c = userService.findConstantByCode(code);
		if(c!=null){
			List<Constant> list = userService.queryConstantBypcode(c.code, null);	
			TreeMap<String, List<Constant>> map = new TreeMap<String,  List<Constant>>();
			for(Constant sc:list){
				JSONArray r = null;
				String initial = getFirst(sc.getConts_name());
			    if(map.containsKey(initial)){
			    	map.get(initial).add(sc);
			    }else{
			    	List<Constant> l = new ArrayList<Constant>();
			    	l.add(sc);
			    	map.put(initial, l);
			    	
			    }
				/**
				JSONObject so = new JSONObject();
				so.put("code",sc.code);
				so.put("name",sc.conts_name);
				so.put("ico","");
				so.put("initial", initial);
				if(o.containsKey(initial)){
					r=o.getJSONArray(initial);
					r.add(so);
				}else{
					r = new JSONArray();
					r.add(so);
					o.put(initial, r);
				}*/
			}
			for(Entry<String, List<Constant>> en:map.entrySet()){
				JSONArray r = new JSONArray();
				for(Constant sc:en.getValue()){
					JSONObject so = new JSONObject();
					so.put("code",sc.code);
					so.put("name",sc.conts_name);
					so.put("ico","");
					so.put("initial", en.getKey());
					r.add(so);
				}
				o.put(en.getKey(), r);
			}
			
			
		}
		Result result = new Result();
		result.put("data", o);
	    return result;
	}
	private String getFirst(String name){
		 Pinyin pinyin = new Pinyin();
		String str = pinyin.getFirstPY(name);
		return str.length()>0?str.substring(0,1):"";
	}


}
